<template>
    <div class="container">
        <Form :model="formItem" label-position="top">
            <div class="title-style">基本信息</div>
            <Row :gutter="16">
                <Col span="12">
                    <FormItem label="商品名称:" prop="name">
                        <div class="form-element">
                            <Input v-model="formItem.name" placeholder="请输入商品名称"/>
                        </div>
                    </FormItem>
                </Col>
                <Col span="12">
                    <FormItem label="商品排序号:" prop="sort">
                        <div class="form-element">
                            <Input v-model="formItem.sort" type="number" placeholder="请输入商品排序号"></Input>
                        </div>
                    </FormItem>
                </Col>
                <Col span="10">
                    <FormItem label="选择已有单位:" prop="">
                        <Select v-model="formItem.unitId" style="width:100%">
                            <Option v-for="item in companyList" :value="item.id" :key="item.id">
                                {{ item.name }}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="2">
                    <FormItem label="新建单位:" prop="">
                        <Button @click="addCompany" type="info">新建</Button>
                    </FormItem>
                </Col>
                <Col span="10">
                    <FormItem label="选择已有分类:" prop="">
                        <Cascader v-model="formItem.classification" :data="classificationList" change-on-select></Cascader>
                    </FormItem>
                </Col>
                <Col span="2">
                    <FormItem label="新建分类:" prop="">
                        <Button @click="addClassification" type="info">新建</Button>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="商品类型:" prop="type">
                        <div class="form-element">
                            <RadioGroup v-model="formItem.type">
                                <Radio label="0" value="0" border>实物商品</Radio>
                                <Radio label="1" value="1" border>服务</Radio>
                                <Radio label="2" value="2" border>虚拟商品</Radio>
                            </RadioGroup>
                        </div>
                    </FormItem>
                </Col>
                <!--                <Col span="4">-->
                <!--                    <FormItem label="是否为赠品:" prop="isGift">-->
                <!--                        <div class="form-element">-->
                <!--                            <RadioGroup v-model="formItem.isGift">-->
                <!--                                <Radio label="0" value="0" border>是</Radio>-->
                <!--                                <Radio label="1" value="1" border>否</Radio>-->
                <!--                            </RadioGroup>-->
                <!--                        </div>-->
                <!--                    </FormItem>-->
                <!--                </Col>-->
                <!--                <Col span="8">-->
                <!--                    <FormItem label="产品属性:">-->
                <!--                        <div class="form-element">-->
                <!--                            <RadioGroup v-model="formItem.commodityType">-->
                <!--                                <Radio label="0" value="0" border>单品</Radio>-->
                <!--                                <Radio label="1" value="1" border>多规格</Radio>-->
                <!--                            </RadioGroup>-->
                <!--                        </div>-->
                <!--                    </FormItem>-->
                <!--                </Col>-->
            </Row>
            <div class="title-style">
                商品规格与库存
                <div class="title-right">
                    <Button style="margin-top: -4px" @click="addSpecifications" type="info">新建</Button>
                </div>
            </div>
            <specifications-stock :formItem="formItem"></specifications-stock>

            <div class="title-style">商品图文信息</div>
            <Row>
                <Col span="24">
                    <FormItem label="商品轮播图:">

                        <wl-upload-oss-files
                                v-model="imgList"
                                :maxNum="50"
                                uploadType="hadoop"
                                @result="resultAction"
                                fileName="origin"
                                :uploadUrl="getUploadUrl"
                                getSignUrl="/api/ac/ctcshop/getHadoopService/getSign"
                                :format="format">
                        </wl-upload-oss-files>
                    </FormItem>
                </Col>
                <Col span="24">
                    <FormItem label="商品详情图:">
                        <wl-upload-oss-files
                                v-model="imgDetailsList"
                                :maxNum="50"
                                uploadType="hadoop"
                                @result="resultAction"
                                fileName="origin"
                                :uploadUrl="getUploadUrl"
                                getSignUrl="/api/ac/ctcshop/getHadoopService/getSign"
                                :format="format">
                        </wl-upload-oss-files>
                    </FormItem>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <FormItem label="商品描述:">
                        <div class="form-element">
                            <Input v-model="formItem.remarks" type="textarea" :rows="4" placeholder=""/>
                        </div>
                    </FormItem>
                </Col>
            </Row>

            <Button @click="save" type="info">保存</Button>
        </Form>
        <Modal style="text-align: center" v-model="modalShow" width="360">
            <Input v-model="insertName" placeholder="请输入单位名称" style="margin-top: 20px"/>
            <div slot="footer">
                <Button type="error" size="large" long :loading="insertLoading" @click="insertAction">保存</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import {
  goodsUnitServiceList,
  goodsUnitServiceInsert,
  CategoryFindList,
  goodsInfoServiceUpdate,
  goodsInfoServiceGet
} from '@/api/shop'
import specificationsStock from './component/specifications-stock/index'

export default {
  data () {
    return {
      tableData: [],
      formItem: {},
      companyList: [],
      modalShow: false,
      insertLoading: false,
      insertName: '',
      classificationList: [],
      specificationsChildrenList: [],

      imgList: '',
      imgDetailsList: '',
      format: ['jpg', 'jpeg', 'png'],
      keyData: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'],
      filterData: {}
    }
  },
  components: { specificationsStock },
  props: {},
  mounted () {
    // 单位
    this.companyListAciton()
    // 分类
    this.classificationAction()
    this.init()
  },
  computed: {
    company_code () {
      return this.$store.state.user.severUserInfo.data.company_code
    },
    getUploadUrl () {
      return this.$config.upLoadFileUrl
    }
  },
  methods: {
    init () {
      goodsInfoServiceGet({ id: this.$route.query.id }).then(res => {
        let data = res.data
        if (data.errcode === 0) {
          this.formItem = data.data
          this.formItem.classification = [
            data.data.parentCategoryId,
            data.data.categoryId
          ]
          if (this.formItem.imgDetailsList.length > 0) {
            for (let i = 0; i < this.formItem.imgDetailsList.length; i++) {
              this.imgDetailsList += this.formItem.imgDetailsList[i].url + ','
            }
          }
          if (this.formItem.imgList.length > 0) {
            for (let i = 0; i < this.formItem.imgList.length; i++) {
              this.imgList += this.formItem.imgList[i].url + ','
            }
          }
          if (this.formItem.skuList.length > 0) {
            let dataList = []
            for (let i = 0; i < this.formItem.skuList.length; i++) {
              if (this.formItem.skuList[i].attrs.length === 1) {
                dataList.push({
                  tableKey1: this.formItem.skuList[i].attrs[0].propertyValue,
                  tableId1: this.formItem.skuList[i].attrs[0].valueId,
                  nameId1: this.formItem.skuList[i].attrs[0].nameId,
                  id: this.formItem.skuList[i].id,
                  price: this.formItem.skuList[i].price,
                  stock: this.formItem.skuList[i].stock
                })
              }
              if (this.formItem.skuList[i].attrs.length === 2) {
                dataList.push({
                  tableKey1: this.formItem.skuList[i].attrs[0].propertyValue,
                  tableId1: this.formItem.skuList[i].attrs[0].valueId,
                  nameId1: this.formItem.skuList[i].attrs[0].nameId,
                  tableKey2: this.formItem.skuList[i].attrs[1].propertyValue,
                  tableId2: this.formItem.skuList[i].attrs[1].valueId,
                  nameId2: this.formItem.skuList[i].attrs[1].nameId,
                  id: this.formItem.skuList[i].id,
                  price: this.formItem.skuList[i].price,
                  stock: this.formItem.skuList[i].stock
                })
              }
              if (this.formItem.skuList[i].attrs.length === 3) {
                dataList.push({
                  tableKey1: this.formItem.skuList[i].attrs[0].propertyValue,
                  tableId1: this.formItem.skuList[i].attrs[0].valueId,
                  nameId1: this.formItem.skuList[i].attrs[0].nameId,
                  tableKey2: this.formItem.skuList[i].attrs[1].propertyValue,
                  tableId2: this.formItem.skuList[i].attrs[1].valueId,
                  nameId2: this.formItem.skuList[i].attrs[1].nameId,
                  tableKey3: this.formItem.skuList[i].attrs[2].propertyValue,
                  tableId3: this.formItem.skuList[i].attrs[2].valueId,
                  nameId3: this.formItem.skuList[i].attrs[2].nameId,
                  id: this.formItem.skuList[i].id,
                  price: this.formItem.skuList[i].price,
                  stock: this.formItem.skuList[i].stock
                })
              }
            }
            console.log(dataList)
            this.formItem.newSkuList = dataList
            for (let i = 0; i < this.formItem.availableAttrs.length; i++) {
              if (this.formItem.newSkuList[0].nameId1 === this.formItem.availableAttrs[i].nameId) {
                this.formItem.availableAttrs[i].sort = '1'
              }
              if (this.formItem.newSkuList[0].nameId2 === this.formItem.availableAttrs[i].nameId) {
                this.formItem.availableAttrs[i].sort = '2'
              }
              if (this.formItem.newSkuList[0].nameId3 === this.formItem.availableAttrs[i].nameId) {
                this.formItem.availableAttrs[i].sort = '3'
              }
            }
            this.formItem.availableAttrs = this.formItem.availableAttrs.sort(this.compare('sort'))
            console.log(this.formItem.availableAttrs.sort(this.compare('sort')), 'availableAttrs')
          }
        } else {
          this.error(data)
        }
      })
    },
    compare (property) {
      return function (a, b) {
        let value1 = a[property]
        let value2 = b[property]
        return value1 - value2
      }
    },
    resultAction (data) {
      let arrData = data.split(',')
      console.log(arrData)
      // if (arrData.length > 0) {
      //   this.filterData = {}
      //   arrData.forEach((item, index) => {
      //     if (item !== undefined && item && item !== 'undefined') {
      //       let arr = this.getUrlImgName(item).split('.')
      //       let arr2 = arr[0].split('-')
      //       let keyMap = this.keyData[arr2[0]] + '_' + this.keyData[arr2[1]]
      //       if (this.filterData[keyMap] !== '' && this.filterData[keyMap] !== undefined) {
      //         this.filterData[keyMap] = this.filterData[keyMap] + ',' + item
      //       } else {
      //         this.filterData[keyMap] = item
      //       }
      //     }
      //   })
      // }
    },
    getUrlImgName (url) {
      let pos = url.lastIndexOf('/')
      if (pos === -1) {
        pos = url.lastIndexOf('\\')
      }
      let filename = url.substr(pos + 1)
      if (filename.indexOf('?') !== -1) {
        let arr = filename.split('?')
        filename = arr[0]
      }
      return filename
    },
    save () {
      if (this.formItem.name === undefined ||
            this.formItem.name === null ||
            this.formItem.name === '') {
        this.$Message.error({
          content: '请输入商品名称！'
        })
        return false
      }
      if (this.formItem.sort === undefined ||
            this.formItem.sort === null ||
            this.formItem.sort === '') {
        this.$Message.error({
          content: '请输入商品排序号！'
        })
        return false
      }
      // 商品默认下架状态
      this.formItem.status = '1'
      if (this.formItem.classification !== undefined &&
          this.formItem.classification !== null &&
          this.formItem.classification !== '' &&
          this.formItem.classification.length === 2
      ) {
        // 分类id 一级
        if (this.formItem.classification[0]) {
          this.formItem.parentCategoryId = this.formItem.classification[0]
        }
        // 分类id 二级
        if (this.formItem.classification[1]) {
          this.formItem.categoryId = this.formItem.classification[1]
        }
      } else {
        this.$Message.error({
          content: '请选择完整分类！'
        })
        return false
      }
      // this.$delete(this.formItem, 'newSkuList')
      // 取出规格中最低价格
      if (this.formItem.skuList !== '' &&
                    this.formItem.skuList !== undefined &&
                    this.formItem.skuList !== null
      ) {
        let dataList = []
        for (let i = 0; i < this.formItem.skuList.length; i++) {
          dataList.push(this.formItem.skuList[i].price)
        }
        console.log(Math.min.apply(Math, dataList))
        this.formItem.price = Math.min.apply(Math, dataList)
      } else {
        this.$Message.error({
          content: '请填写库存及价格！'
        })
        return false
      }
      // 图片
      if (this.imgList !== undefined) {
        let dataList = this.$common.xeUtils.clone(this.imgList)
        dataList = dataList.substr(0, dataList.length - 1)
        console.log(dataList)
        console.log(dataList.split(','))
        dataList = dataList.split(',')
        this.formItem.imgList = []
        for (let i = 0; i < dataList.length; i++) {
          this.formItem.imgList.push({
            url: dataList[i],
            thumb: dataList[i],
            sort: i,
            type: '0'
          })
        }
      }
      if (this.imgDetailsList !== undefined) {
        let dataList = this.$common.xeUtils.clone(this.imgDetailsList)
        dataList = dataList.substr(0, dataList.length - 1)
        console.log(dataList)
        console.log(dataList.split(','))
        dataList = dataList.split(',')
        this.formItem.imgDetailsList = []
        for (let i = 0; i < dataList.length; i++) {
          this.formItem.imgDetailsList.push({
            url: dataList[i],
            thumb: dataList[i],
            sort: i,
            type: '1'
          })
        }
      }
      // this.formItem.imgList = this.formItem.imgList.substr(0, this.formItem.imgList.length - 1)
      // console.log(this.formItem.imgList)
      // console.log(this.formItem.imgList.split(','))
      this.saveAction()
    },
    saveAction () {
      goodsInfoServiceUpdate(this.formItem).then(ret => {
        if (ret.data.errcode === 0) {
          this.success('添加成功')
          // localStorage.setItem('formItem', this.formItem)
          this.$router.push({
            name: 'shopCommodityList'
          })
        } else {
          this.error(ret.data)
        }
      })
    },
    classificationAction () {
      this.tableLoading = true
      CategoryFindList().then(ret => {
        if (ret.data.errcode === 0) {
          let dataList = ret.data.data
          for (let i = 0; i < dataList.length; i++) {
            dataList[i].value = dataList[i].id
            dataList[i].label = dataList[i].name
            if (dataList[i].childrenList) {
              dataList[i].children = dataList[i].childrenList
              for (let j = 0; j < dataList[i].children.length; j++) {
                dataList[i].children[j].value = dataList[i].children[j].id
                dataList[i].children[j].label = dataList[i].children[j].name
              }
            }
          }
          console.log(dataList)
          this.classificationList = dataList
        }
      })
    },
    addClassification () {
      console.log(this.formItem)
      this.$router.push({
        name: 'shopClassification',
        query: { returnType: '1', commodityId: this.$route.query.id }
      })
    },
    addSpecifications () {
      console.log(this.formItem)
      this.$router.push({
        name: 'shopSpecificationsAdd',
        query: { returnType: '1', commodityId: this.$route.query.id }
      })
    },
    addCompany () {
      this.modalShow = true
    },
    insertAction () {
      if (this.insertName === '' || this.insertName === null || this.insertName === undefined) {
        this.$Message.error('请输入单位名称')
        return false
      }
      this.insertLoading = true
      goodsUnitServiceInsert({ name: this.insertName }).then(res => {
        let data = res.data
        if (data.errcode === 0) {
          this.companyListAciton()
          console.log(data.data.result)
          this.formItem.unitId = data.data.result
          this.insertLoading = false
          this.modalShow = false
          this.success('添加成功')
        } else {
          this.error(data)
        }
      })
    },
    companyListAciton () {
      goodsUnitServiceList({ pageNo: '1', pageSize: '100' }).then(ret => {
        let data = ret.data
        if (data.errcode === 0) {
          this.companyList = data.data.result
        } else {
          this.error(data)
        }
      })
    },
    success (val) {
      val = this.$common.xeUtils.isEmpty(val) ? '操作成功' : val
      this.$Message.success(val)
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    }
  }

}
</script>

<style scoped>
    .container {
        padding-bottom: 50px;
        background-color: white;
        padding: 16px;
    }

    .container > .opt-area {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-bottom: 5px;
        border-bottom: 1px solid #c3c3c3;
    }

    .container > .opt-area > .left-con {
        font-size: 14px;
    }

    .container > .opt-area > .right-con {
        display: flex;
    }

    .container > .opt-area > .right-con > Button:not(:last-child) {
        margin-right: 5px;
    }

    .container .title {
        font-size: 14px;
        margin-bottom: 3px;
        display: flex;
        align-items: center;
    }

    .container .title > span {
        font-size: 12px;
        color: red;
        margin-right: 3px;
    }

    .container .form-element {
        display: flex;
        align-items: center;
        line-height: 32px;
    }

    .button-group {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
    }

    .button-group > Button:not(:last-child) {
        margin-right: 10px;
    }

    .title-style {
        padding: 8px 12px;
        background-color: #ecf8ff;
        border-radius: 4px;
        border-left: 5px solid #50bfff;
        margin: 15px 0;
        font-size: 16px;
        width: 100%;
    }

    .container >>> .ivu-switch-large {
        width: 63px;
    }

    .container >>> .ivu-switch-large.ivu-switch-checked:after {
        left: 42px;
    }
    .title-right{
        float: right;
    }
</style>
